<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('编辑实验报告管理')"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: summernote-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-report-add" th:object="${experimentReport}" enctype="multipart/form-data">
        <input type="hidden" th:field="*{reportId}">

        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">报告标题：</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" th:field="*{reportTitle}" placeholder="请输入报告标题">
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">报告内容：</label>
                <div class="col-sm-8">
                    <input type="hidden" th:field="*{reportContent}">
                    <div class="summernote" id="reportContent" th:attr="data-content=${experimentReport.reportContent}"></div>
                </div>
            </div>
        </div>

        <!-- 附件上传优化部分（支持回显） -->
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">报告附件：</label>
                <div class="col-sm-8">
                    <input type="hidden" th:field="*{filePath}" id="filePath">
                    <div class="input-group">
                        <input type="file" class="form-control" id="fileUpload" accept=".doc,.docx,.pdf,.zip,.rar,.txt">
                        <span class="input-group-addon" style="cursor: pointer;" onclick="uploadFile()">
                            <i class="fa fa-upload"></i> 上传
                        </span>
                    </div>
                    <div class="help-block m-t-xs" id="fileInfo" style="margin-top: 5px;">
                        <th:block th:if="${not #strings.isEmpty(experimentReport.filePath)}">
                            <i class="fa fa-file text-primary"></i> 已上传：
                            <a th:href="@{${experimentReport.filePath}}" target="_blank" th:text="${#strings.substringAfterLast(experimentReport.filePath, '/')}"></a>
                            <button type="button" class="btn btn-link btn-xs text-danger" onclick="removeFile()">
                                <i class="fa fa-trash-o"></i> 移除
                            </button>
                        </th:block>
                        <th:block th:unless="${not #strings.isEmpty(experimentReport.filePath)}">
                            支持格式：doc, docx, pdf, zip, rar, txt
                        </th:block>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">提交时间：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input type="text" class="form-control" th:field="*{submitTime}" placeholder="yyyy-MM-dd">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">成绩：</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" th:field="*{score}" placeholder="请输入成绩">
                </div>
            </div>
        </div>

        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label">评语：</label>
                <div class="col-sm-8">
                    <textarea class="form-control" th:field="*{comment}" rows="3" placeholder="请输入评语"></textarea>
                </div>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: datetimepicker-js"/>
<th:block th:include="include :: summernote-js"/>
<script th:inline="javascript">
    var prefix = ctx + "college/report"

    $("#form-report-add").validate({
        focusCleanup: true
    });

    function submitHandler() {
        if ($.validate.form()) {
            // 处理文件上传表单提交
            var formData = new FormData($('#form-report-add')[0]);
            $.ajax({
                url: prefix + "/add",
                type: "post",
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                dataType: "json",
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess("操作成功");
                        $.operate.closeCurrentTab();
                    } else {
                        $.modal.msgError(result.msg);
                    }
                }
            });
        }
    }

    // 初始化日期选择器并回显数据
    $("input[name='submitTime']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    // 初始化富文本编辑器并回显内容
    $(function() {
        var summernoteElement = $('.summernote');
        var initialContent = summernoteElement.data('content') || '';

        summernoteElement.summernote({
            lang: 'zh-CN',
            dialogsInBody: true,
            height: 300,
            callbacks: {
                onChange: function(contents, $edittable) {
                    $("input[name='" + this.id + "']").val(contents);
                },
                onImageUpload: function(files) {
                    var obj = this;
                    var data = new FormData();
                    data.append("file", files[0]);
                    $.ajax({
                        type: "post",
                        url: ctx + "common/upload",
                        data: data,
                        cache: false,
                        contentType: false,
                        processData: false,
                        dataType: 'json',
                        success: function(result) {
                            if (result.code == web_status.SUCCESS) {
                                $('#' + obj.id).summernote('insertImage', result.url);
                            } else {
                                $.modal.alertError(result.msg);
                            }
                        },
                        error: function(error) {
                            $.modal.alertWarning("图片上传失败。");
                        }
                    });
                }
            }
        });

        // 设置初始内容
        if (initialContent) {
            summernoteElement.summernote('code', initialContent);
        }
    });

    // 文件上传处理函数
    function uploadFile() {
        var file = document.getElementById("fileUpload").files[0];
        if (!file) {
            $.modal.alertWarning("请先选择文件");
            return;
        }

        // 验证文件大小（限制50MB）
        if (file.size > 50 * 1024 * 1024) {
            $.modal.alertWarning("文件大小不能超过50MB");
            return;
        }

        var formData = new FormData();
        formData.append("file", file);

        $.ajax({
            type: "post",
            url: ctx + "common/upload",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            dataType: 'json',
            beforeSend: function() {
                $("#fileInfo").html('<i class="fa fa-spinner fa-spin"></i> 正在上传...');
            },
            success: function(result) {
                if (result.code == web_status.SUCCESS) {
                    $("#filePath").val(result.url);
                    $("#fileInfo").html(
                        '<i class="fa fa-check text-success"></i> 上传成功：' +
                        '<a href="' + result.url + '" target="_blank">' + file.name + '</a> ' +
                        '<button type="button" class="btn btn-link btn-xs text-danger" onclick="removeFile()">' +
                        '<i class="fa fa-trash-o"></i> 移除</button>'
                    );
                } else {
                    $("#fileInfo").html('<i class="fa fa-times text-danger"></i> 上传失败：' + result.msg);
                }
            },
            error: function() {
                $("#fileInfo").html('<i class="fa fa-times text-danger"></i> 上传失败，请重试');
            }
        });
    }

    // 移除已上传文件
    function removeFile() {
        $("#filePath").val("");
        $("#fileInfo").html("支持格式：doc, docx, pdf, zip, rar, txt");
        $("#fileUpload").val("");
    }

    // 显示选中的文件名
    document.getElementById("fileUpload").addEventListener("change", function() {
        if (this.files.length > 0) {
            $("#fileInfo").html("选中文件：" + this.files[0].name +
                ' <span class="text-muted">(点击上传按钮完成上传)</span>');
        }
    });
</script>
</body>
</html>